package org.dce.screencapturer.actions.objects;

import java.awt.BasicStroke;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;

import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JList;

import org.dce.screencapturer.actions.DropDownAction;
import org.dce.screencapturer.objects.DrawingObject;
import org.dce.screencapturer.objects.LineAttributes;
import org.dce.screencapturer.objects.ShapeObject;
import org.dce.screencapturer.util.IconFactory;

@SuppressWarnings("serial")
public class SelectLineWeightAction extends DropDownAction {
	
	public SelectLineWeightAction() {
		super("categories.object", "actions.selectLineWeight", IconFactory.getIcon("/images/font.png"));
		

		DefaultListModel model = new DefaultListModel();
		for (float i=1;i<=10f;i+=0.5f){
			model.addElement(i);
		}
		setModel(model);
		setRenderer(new StrokeRenderer());
	}

	@Override
	protected void itemSelected(Object object) {
		
		Float weight = (Float)object;
		
		ShapeObject shapeObject = (ShapeObject)getObject();
		
		LineAttributes lineAttributes = (LineAttributes) shapeObject.getLineAttributes().clone();
		
		BasicStroke currentStroke = lineAttributes.getStroke();
		
		BasicStroke stroke = new BasicStroke(
			weight, 
			currentStroke.getEndCap(), 
			currentStroke.getLineJoin(), 
			currentStroke.getMiterLimit(), 
			currentStroke.getDashArray(), 
			currentStroke.getDashPhase());
		
		lineAttributes.setStroke(stroke);
		
		shapeObject.setLineAttributes(lineAttributes);
		
		System.out.println(object);
	}

	private class StrokeRenderer 
		extends DefaultListCellRenderer {

		private Float value;
		@Override
		public Component getListCellRendererComponent(JList list, Object value,
				int index, boolean isSelected, boolean cellHasFocus) {

			Component component = super.getListCellRendererComponent(list, value, index, isSelected,
					cellHasFocus);
			
			component.setPreferredSize(new Dimension(60,22));

			this.value = (Float)value;
			
			return component;
		}
		
		protected void paintComponent(Graphics g){
			g.setColor(getBackground());
			g.fillRect(0,0,getWidth()-1,getHeight()-1);
			g.setColor(getForeground());
			
			if (value != null){
				BasicStroke stroke = new BasicStroke(value);
				
				Graphics2D g2d = (Graphics2D)g;
				
				g2d.setStroke(stroke);
				
				Insets insets = getInsets();
				
				g2d.drawLine(insets.left, getHeight()/2, getWidth()-insets.right, getHeight()/2);
			}
		}
		
	}
	

	@Override
	protected boolean acceptObject(DrawingObject anObject) {
		return anObject instanceof ShapeObject;
	}
	
}
